package cn.yanhu.kuwanapp.http.intercept

import cn.woochen.comlib.util.ApplicationUtil
import cn.woochen.comlib.util.ConfigPref
import cn.woochen.comlib.util.PackageUtil
import cn.woochen.comlib.util.UserPref
import cn.yanhu.kuwanapp.utils.ChannelUtils
import cn.yanhu.kuwanapp.utils.DeviceInfoUtil
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 *url拦截器
 *@author woochen
 *@time 2019/4/26 10:29
 */
class UrlInterceptor : Interceptor {
    private var mToken by UserPref(Constants.USER_TOKEN, "")
    private var mImei by UserPref(Constants.IMEI, "")
    private var mDeviceOaid by ConfigPref(Constants.DEVICE_OAID, "")

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request()
        var imei = mImei
        if (imei.isBlank()) imei = DeviceInfoUtil.getIMEI(ApplicationUtil.context)
        var deviceCode = if (mDeviceOaid.isNotBlank()) mDeviceOaid else imei
        //构建新的请求
        val newRequest = request.newBuilder()
            .addHeader("token", mToken)
            .addHeader("appversion", PackageUtil.getCurrentVersionName(ApplicationUtil.context))//版本号
            .addHeader("packagename", ApplicationUtil.context.packageName)//包名
            .addHeader("os", "1")//客户端类型 1安卓 2ios
            .addHeader("channel", ChannelUtils.getChannel())//针对包设置的渠道
            .addHeader("deviceId", imei)//针对包设置的渠道
            .addHeader("udid", deviceCode)
            .addHeader("deviceCode", deviceCode)
            .addHeader("oaid", mDeviceOaid)//oaid
            .addHeader("clientid", "")//推送的设备标识
            .url(request.url)
            .build()
        return chain.proceed(newRequest)
    }

}